package com.bruce.tool.address.spider.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Properties;

@Configuration
@SuppressWarnings("all")
@EnableTransactionManagement
public class AddressConfig {

    @Bean
    @ConfigurationProperties(prefix = "datasource.address")
    public Properties addressDataSourceProperties() {
        return new Properties();
    }

    @Bean
    public DataSource addressDataSource(@Autowired @Qualifier("addressDataSourceProperties") Properties properties) throws SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDbType(properties.getProperty("dbType"));
        dataSource.setUsername(properties.getProperty("username"));
        dataSource.setPassword(properties.get("password").toString());
        dataSource.setUrl(properties.getProperty("url"));
        dataSource.setDriverClassName(properties.getProperty("driver-class-name"));
        dataSource.setMaxActive(Integer.valueOf(properties.getProperty("maxActive")));
        dataSource.setMinIdle(Integer.valueOf(properties.getProperty("minIdle")));
        dataSource.setInitialSize(Integer.valueOf(properties.getProperty("initialSize")));
        dataSource.setMaxWait(Integer.valueOf(properties.getProperty("maxWait")));
        return dataSource;
    }

    @Bean
    public SqlSessionFactory addressSqlSessionFactory(@Qualifier("addressDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        // mybatis的配置  替代mybatis-config.xml文件
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        bean.setConfiguration(configuration);
        return bean.getObject();
    }

    @Bean
    public SqlSessionTemplate addressSqlSessionTemplate(@Qualifier("addressSqlSessionFactory") SqlSessionFactory sessionFactory) {
        return new SqlSessionTemplate(sessionFactory);
    }
}
